package com.tepth.busfix.network.observer;

import com.tepth.busfix.base.BaseView;
import com.tepth.busfix.network.ApiModel;
import com.tepth.busfix.network.config.ErrorCode;
import com.tepth.busfix.network.exception.NoNetworkException;
import com.tepth.busfix.network.exception.TokenInvalidException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.observers.DisposableObserver;

/**
 * Created by 张宇 on 2017/3/13.
 */

public abstract class SimpleDisposableObserver<T> extends DisposableObserver<T> {
    private BaseView mView;

    public SimpleDisposableObserver(BaseView view) {
        mView = view;
    }

    public abstract void onSucceed(Object o);

    @Override
    public void onError(Throwable e) {
        if (e instanceof NoNetworkException) {
            mView.onNetworkError("网络连接错误!");
        } else if (e instanceof ConnectException) {
            mView.onError("服务器连接超时!");
        } else if (e instanceof TokenInvalidException) {
            mView.onTokenInvalid(e.getMessage());
        } else if (e instanceof SocketTimeoutException) {
            mView.onError("服务器连接超时!");
        } else if (e instanceof IllegalStateException) {
            mView.onError("数据格式错误!");
        } else {
            mView.onError(e.getMessage());
        }
    }

    @Override
    public void onNext(T value) {
        ApiModel apiModel = (ApiModel) value;
        String resultCode = apiModel.getResultCode();
        if (ErrorCode.SUCCEED.equals(resultCode)) {
            onSucceed(apiModel.getResult());
        } else if (ErrorCode.TOKEN_INVALID.equals(resultCode)) {
            mView.onTokenInvalid(apiModel.getResultMsg());
        } else {
            mView.onError(apiModel.getResultMsg());
        }
    }

    @Override
    public void onComplete() {

    }

}
